# -*- coding: UTF-8 -*-
from config.Config import Config
import os
from constant import constant_define
from dao.MySqlDAL import MySqlDAL

import requests
import utils.CookieUtils as cu
__author__ = 'shudong.msd'

'''
    初始化股票id,name等信息

    http://xueqiu.com/stock/screener/screen.json?category=SH&size=2799&order=desc&orderby=follow7d&current=ALL&pct=ALL&follow7d=ALL&_=1443142974231
'''

# # 获取所有股票名字
# stock_file = FileHandler()
#
# stock_list = stock_file.get_stock_info(os.path.join(os.path.pardir, 'utils/stock.txt'))
#
# for row in stock_list:
#     print row[0], row[1]
#
#


headers = {
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding':'gzip, deflate, sdch',
        'Accept-Language':'zh-CN,zh;q=0.8,en;q=0.6',
        'cache-control':'no-cache',
        'Connection':'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36',
        'Referer':'http://xueqiu.com/hq/screener/CN',
        'Host':'xueqiu.com',
        'X-Requested-With':'XMLHttpRequest',
        'Upgrade-Insecure-Requests':'1',
        'Cookie': cu.init_cookie()
}


target_url = 'http://xueqiu.com/stock/screener/screen.json?category=SH&size=4000&order=desc&orderby=follow7d&current=ALL&pct=ALL&follow7d=ALL'

def init_stock():
    global target_url
    global headers
    req = requests.get(target_url,headers=headers).json()

    stock_list = list()

    for item in req['list']:
        tmp = (item['symbol'],item['name'])
        if tmp in stock_list:
            continue
        stock_list.append(tmp)

    # stock_list.sort()

    # print stock_list

    # 插入db
    sqlDao = MySqlDAL()
    res = sqlDao.get_dimensions_rows('SELECT stock_id FROM tb_stock_info')
    source_data = []
    tmp_list = [row['stock_id'] for row in res]
    for item in stock_list:
        if item[0] not in tmp_list:
            source_data.append(item)

    num = sqlDao.insert_many_batch(['stock_id','stock_name'], source_data, 'tb_stock_info',80)

    return num


# print init_stock()